/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2016 abel533@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.myhouse.controller;

import com.github.pagehelper.PageInfo;
import com.myhouse.model.House;
import com.myhouse.service.HouseService;
import com.myhouse.util.JpaPageInfo;
import com.myhouse.util.LoggerUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

//@Controller
@RestController
@RequestMapping("/houses")
public class HouseController {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
    @Autowired
    private HouseService houseService;
    
    @RequestMapping
    public ModelAndView getAll(House house,HttpServletRequest request) {
        ModelAndView result = new ModelAndView("index");
        Page<House> houseList = houseService.getAllPage(house);
        result.addObject("pageInfo", JpaPageInfo.of(houseList));
        
        result.addObject("queryParam", house);
        
        //用于日志拦截器，日志打印
        request.setAttribute(LoggerUtils.LOGGER_RETURN,houseList);
//        logger.debug("[debug]parm is: " + house);
//        logger.info("[info]parm is: " + house);
//        logger.warn("[warn]parm is: " + house);
//        logger.error("[error]parm is: " + house);
        
        return result;
    }

    @RequestMapping(value = "/add")
    public ModelAndView add() {
        ModelAndView result = new ModelAndView("view");
        result.addObject("house", new House());
        return result;
    }

    @RequestMapping(value = "/view/{id}")
    public ModelAndView view(@PathVariable Integer id) {
        ModelAndView result = new ModelAndView("view");
        Optional<House> houseOptional = houseService.getById(id); 
        House house = houseOptional.orElse(new House()); //如果创建的Optional中有值存在，则返回此值，否则返回一个默认值
        result.addObject("house", house);
        return result;
    }

    @RequestMapping(value = "/delete/{id}")
    public ModelAndView delete(@PathVariable Integer id, RedirectAttributes ra) {
        ModelAndView result = new ModelAndView("redirect:/houses");
        houseService.deleteById(id);
        ra.addFlashAttribute("msg", "删除成功!");
        return result;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView save(House house) {
        ModelAndView result = new ModelAndView("view");
        String msg = house.getId() == null ? "新增成功!" : "更新成功!";
        //SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        house.setTime(new Date());
        house.setState(0);
        houseService.save(house);
        result.addObject("house", house);
        result.addObject("msg", msg);
        return result;
    }
    

    //http://127.0.0.1:8080/houses/all
    @ResponseBody
    @RequestMapping(value="/all")
    public Page<House> getAll1() {
    	House house = new House();
    	
        Page<House> houseList = houseService.getAllPage(house);
        //System.out.println(houseList);
        for(House h : houseList){        	
        	System.out.println(h);
        }
        return houseList;
    }
    /*
     Could not resolve view with name 'houses/all' in servlet with name 'dispatcherServlet':
     原因：因为返回信息为json对象，本人在controller方法所在的入口类上，添加的注解为：@Controller, 需要在方法上添加@ResponseBody注解或类修改为@RestController
     */
    
    
}
